package service

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"strings"
	"time"
	"user-srv/basic/global"
	__ "user-srv/basic/proto"
	"user-srv/internal/model"
	"user-srv/pkg"
)

type Service struct {
	__.UnimplementedUserServer
}

// 套餐展示
func (s *Service) MemberPlan(ctx context.Context, req *__.MemberPlanReq) (resp *__.MemberPlanResp, err error) {
	var members []model.Member
	query := global.DB.Model(&model.Member{})

	// 如果 req.type > 0，按类型过滤
	if req.Type > 0 {
		query = query.Where("types = ?", req.Type)
	}

	if err = query.Find(&members).Error; err != nil {
		return nil, err
	}

	// 转换成 proto 定义的返回结构
	var planList []*__.MemberPlanItem
	for _, m := range members {
		planList = append(planList, &__.MemberPlanItem{
			PlanId:   int64(m.ID),
			Name:     m.Name,
			Price:    float32(m.Price), // float64 → float32
			Duration: int64(m.Duration),
		})
	}

	resp = &__.MemberPlanResp{
		MemberPlanList: planList,
	}
	return resp, nil
}

// 创建充值记录并创建订单以及支付
func (s *Service) CreateOrder(ctx context.Context, req *__.CreateOrderReq) (resp *__.CreateOrderResp, err error) {

	var member model.Member
	if err = global.DB.First(&member, req.MemberId).Error; err != nil {
		return nil, fmt.Errorf("会员套餐不存在")
	}

	orderNo := GetOrderSn(int64(req.UserId))

	var user model.User
	if err = global.DB.Debug().Where("id = ?", req.UserId).First(&user).Error; err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	// 1先创建充值记录（状态待支付）
	record := &model.Recharge{
		OrderNo:  orderNo,
		UserID:   uint(req.UserId),
		QQNumber: user.Number,
		MemberID: uint(req.MemberId),
		PayType:  1, // 支付宝
		Amount:   member.Price,
		Status:   0, // 待支付
	}
	if err = global.DB.Create(record).Error; err != nil {
		return nil, err
	}

	// 写入数据库
	order := &model.Order{
		OrderNo:  orderNo,
		UserID:   uint(req.UserId),
		MemberID: uint(req.MemberId),
		Amount:   member.Price,
		PayType:  1,
		Status:   0, // 待支付
	}

	if err = global.DB.Create(order).Error; err != nil {
		return nil, err
	}

	payURL, err := pkg.ALiPay("QQ会员充值", orderNo, fmt.Sprintf("%.2f", member.Price))
	if err != nil {
		return nil, err
	}

	resp = &__.CreateOrderResp{
		OrderId: uint64(order.ID),
		OrderNo: orderNo,
		PayUrl:  payURL,
	}
	return resp, nil
}

// 随机唯一订单
func GetOrderSn(userId int64) string {
	NowTime := time.Now().Format("060102150405")
	User := fmt.Sprintf("%04d", userId%10000)
	str := uuid.New().String()
	uuidStr := strings.Replace(str, "-", "", -1)
	uuidStr = uuidStr[:4]
	sn := fmt.Sprintf("%s%s%s", NowTime, User, uuidStr)
	return sn
}

// 支付成功更新各表数据
func (s *Service) PayOrderSuccess(_ context.Context, req *__.PayOrderSuccessReq) (resp *__.PayOrderSuccessResp, err error) {
	// 1. 查询订单
	var order model.Order
	if err = global.DB.Where("order_no = ?", req.OrderNo).First(&order).Error; err != nil {
		return nil, fmt.Errorf("订单不存在: %v", err)
	}

	// 判断订单是否已经支付过，避免重复写充值记录
	if order.Status == 1 {
		return nil, fmt.Errorf("订单已支付")
	}

	// 2️⃣ 查询充值记录
	var record model.Recharge
	if err = global.DB.Where("order_no = ?", req.OrderNo).First(&record).Error; err != nil {
		return nil, fmt.Errorf("充值记录不存在: %w", err)
	}

	// 3️⃣ 查询用户
	var user model.User
	if err = global.DB.First(&user, order.UserID).Error; err != nil {
		return nil, fmt.Errorf("用户不存在: %w", err)
	}

	// 4️⃣ 查询套餐信息
	var member model.Member
	if err = global.DB.First(&member, order.MemberID).Error; err != nil {
		return nil, fmt.Errorf("套餐不存在: %w", err)
	}

	// 2. 更新订单状态为已支付
	if err = global.DB.Model(&order).Update("status", 1).Error; err != nil {
		return nil, fmt.Errorf("更新订单状态失败: %v", err)
	}

	// 更新充值记录状态
	if err = global.DB.Model(&model.Recharge{}).Where("order_no = ?", req.OrderNo).Update("status", 1).Error; err != nil {
		return nil, err
	}

	// 7️⃣ 更新用户会员到期时间（天数单位）

	duration := int64(member.Duration) // 套餐天数

	if user.MemberExpireTime > 0 {
		// 会员未过期，叠加剩余天数
		user.MemberExpireTime += duration
	} else {
		// 会员过期，从今天开始计算
		user.MemberExpireTime = duration
	}

	if err = global.DB.Model(&user).Update("member_expire_time", user.MemberExpireTime).Error; err != nil {
		return nil, fmt.Errorf("更新用户会员到期时间失败: %w", err)
	}

	resp = &__.PayOrderSuccessResp{
		Success: true,
		Message: "生成成功",
	}

	return resp, nil
}

// 支付记录查询
func (s *Service) MemberPlanReChargeRecord(_ context.Context, req *__.MemberPlanReChargeRecordReq) (*__.MemberPlanReChargeRecordResp, error) {

	var user model.User
	if err := global.DB.Debug().Where("id = ?", req.UserId).First(&user).Error; err != nil {
		return nil, fmt.Errorf("用户不存在")
	}
	// 在查询用户后添加
	fmt.Printf("用户ID: %d, Number值: %s\n", req.UserId, user.Number)

	var records []model.Recharge
	if err := global.DB.Where("user_id = ?", req.UserId).Order("created_at desc").Find(&records).Error; err != nil {
		return nil, err
	}

	var RecordList []*__.MemberPlanReChargeRecordItem

	for _, r := range records {
		list := &__.MemberPlanReChargeRecordItem{
			ChargeId: int64(r.ID),
			PlanId:   int64(r.MemberID),
			UserId:   int64(r.UserID),
			PayType:  r.PayType,
			Price:    float32(r.Amount),
			Number:   user.Number,
		}
		RecordList = append(RecordList, list)
	}

	resp := &__.MemberPlanReChargeRecordResp{
		RecordList: RecordList,
	}

	return resp, nil
}
